package cn.zyq.ykb.controller.mgt.system;


import cn.zyq.ykb.beans.sys.SysAdmin;
import cn.zyq.ykb.service.sys.SysAdminService;
import cn.zyq.ykb.system.annotation.Log;
import cn.zyq.ykb.system.common.BaseController;
import cn.zyq.ykb.system.config.consts.system.SystemConfig;
import cn.zyq.ykb.system.exception.BusinessException;
import cn.zyq.ykb.system.ry.enums.BusinessType;
import cn.zyq.ykb.system.ry.model.LoginUser;
import cn.zyq.ykb.system.ry.security.handle.AjaxResult;
import cn.zyq.ykb.system.ry.security.service.TokenService;
import cn.zyq.ykb.system.ry.util.SecurityUtils;
import cn.zyq.ykb.system.ry.util.StringUtils;
import cn.zyq.ykb.system.ry.util.file.FileUploadUtils;
import cn.zyq.ykb.system.ry.util.file.MimeTypeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 个人信息 业务处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/mgt/system/profile")
public class SysProfileController extends BaseController {
    @Autowired
    private SysAdminService sysAdminService;

    @Autowired
    private TokenService tokenService;

    /**
     * 个人信息
     */
    @GetMapping
    public Object profile() {
        LoginUser loginUser = getMgtLoginUser();
        SysAdmin user = loginUser.getSysAdmin();
        AjaxResult ajax = AjaxResult.success(user);
        ajax.put("roleGroup", sysAdminService.selectUserRoleGroup(loginUser.getUsername()));
        ajax.put("postGroup", sysAdminService.selectUserPostGroup(loginUser.getUsername()));
        return ajax;
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public void updateProfile(@RequestBody SysAdmin sysAdmin) {
        LoginUser loginUser = getMgtLoginUser();
        SysAdmin sysUser = loginUser.getSysAdmin();
        sysAdmin.setUserName(sysUser.getUserName());
        if (StringUtils.isNotEmpty(sysAdmin.getPhonenumber()) && !sysAdminService.checkPhoneUnique(sysAdmin)) {
            throw new BusinessException("修改用户'" + sysAdmin.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(sysAdmin.getEmail()) && !sysAdminService.checkEmailUnique(sysAdmin)) {
            throw new BusinessException("修改用户'" + sysAdmin.getUserName() + "'失败，邮箱账号已存在");
        }
        sysAdmin.setSysAdminID(sysUser.getSysAdminID());
        sysAdmin.setPassword(null);
        sysAdmin.setAvatar(null);
        sysAdmin.setSysDeptID(null);
        if (sysAdminService.updateUserProfile(sysAdmin) > 0) {
            // 更新缓存用户信息
            sysUser.setNickName(sysAdmin.getNickName());
            sysUser.setPhonenumber(sysAdmin.getPhonenumber());
            sysUser.setEmail(sysAdmin.getEmail());
            sysUser.setSex(sysAdmin.getSex());
            tokenService.setLoginUser(loginUser);
        }
        throw new BusinessException("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public void updatePwd(String oldPassword, String newPassword) {
        LoginUser loginUser = getMgtLoginUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            throw new BusinessException("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            throw new BusinessException("新密码不能与旧密码相同");
        }
        if (sysAdminService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0) {
            // 更新缓存用户密码
            loginUser.getSysAdmin().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);

        }
//        throw new BusinessException("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public Object avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            LoginUser loginUser = getMgtLoginUser();
            String avatar = FileUploadUtils.upload(SystemConfig.fileBasePath, file, MimeTypeUtils.IMAGE_EXTENSION);
            if (sysAdminService.updateUserAvatar(loginUser.getUsername(), avatar)) {
                Map ajax = new HashMap();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getSysAdmin().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        throw new BusinessException("上传图片异常，请联系管理员");
    }
}
